package com.wxy.bytebuffer;

import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;

/**
 * @author 47868
 */
public class StringToByteBuffer {
    public static void printBuffer(ByteBuffer buffer) {
        while (buffer.hasRemaining()) {
            System.out.print((char) buffer.get());
        }
        System.out.println("\n----------------------------------");
        buffer.compact();
    }
    public static void main(String[] args) {
        ByteBuffer buffer1 = ByteBuffer.allocate(16);
        //1.转换为字节
        buffer1.put("hello".getBytes());
        buffer1.flip();
        printBuffer(buffer1);

        //2.使用StandardCharsets
        // 使用StandardCharsets将字符串转为buffer后会自动切换到读模式
        buffer1 = StandardCharsets.UTF_8.encode("hello world");
        printBuffer(buffer1);

        //3.使用wrap
        // 直接切换到读模式
        buffer1 = ByteBuffer.wrap("world".getBytes());
        printBuffer(buffer1);
        buffer1.rewind();   //将position位置重置
        // 将buffer转换为字符串
        String string = StandardCharsets.UTF_8.decode(buffer1).toString();
        System.out.println(string);
    }
}
